package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.Destination;
import cn.wolfcode.wolf2world.domain.Region;
import cn.wolfcode.wolf2world.domain.Strategy;
import cn.wolfcode.wolf2world.domain.StrategyCatalog;
import cn.wolfcode.wolf2world.query.DestinationQueryObject;
import cn.wolfcode.wolf2world.repository.DestinationRepository;
import cn.wolfcode.wolf2world.service.*;
import cn.wolfcode.wolf2world.utils.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020/8/9 20:09
 */
@Service
public class DestinationServiceImpl implements DestinationService {
    @Autowired
    private DestinationRepository destinationRepository;
    @Autowired
    private RegionService regionService;
    @Autowired
    private StrategyCatalogService strategyCatalogService;
    @Autowired
    private StrategyService strategyService;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void insert(Destination destination) {
        destination.setId(null);
        destinationRepository.insert(destination);
    }

    @Override
    public void update(Destination destination) {
        destinationRepository.save(destination);
    }

    @Override
    public void delete(String id) {
        destinationRepository.deleteById(id);
    }

    @Override
    public Destination get(String id) {
        return destinationRepository.findById(id).orElse(null);
    }

    @Override
    public List<Destination> list() {
        return destinationRepository.findAll();
    }

    /**
     * 高级查询
     * @param qo 查询条件
     * @return
     */
    @Override
    public Page<Destination> query(DestinationQueryObject qo) {

        //查询对象
        Query query = new Query();
        if (StringUtils.hasLength(qo.getKeyword())) {
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }

        if (StringUtils.hasLength(qo.getParentId())) {
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }else {
            query.addCriteria(Criteria.where("parentId").is(null));
        }

        return DBHelper.getPage(mongoTemplate, query, qo, Destination.class, Sort.Direction.ASC, "_id");
    }

    /**
     * 根据区域id查询关联的目的地
     * @param rid
     * @return
     */
    @Override
    public List<Destination> queryByRegionId(String rid) {
        Region region = regionService.get(rid);
        return (List<Destination>) destinationRepository.findByIdIn(region.getRefIds());
    }

    /**
     * 根据id更新目的地简介
     * @param id
     * @param info
     * @return
     */
    @Override
    public void updateInfo(String id, String info) {
        //全量更新 TODO 1.做局部更新  2.更新到elasticsearch
        /*Destination destination = this.get(id);
        destination.setInfo(info);
        this.update(destination);*/
        //局部更新
        Update update = Update.update("info", info);
        mongoTemplate.updateMulti(Query.query(Criteria.where("id").is(id)),update,Destination.class);
    }

    /**
     * 循环或者递归查询父目的地
     *
     * @param destId
     * @return
     */
    @Override
    /*public List<Destination> createToasts(List<Destination> arrayList, String parentId) {
        //跳出递归的条件
        if (!StringUtils.hasLength(parentId)) {
            return arrayList;
        }
        Destination destination = this.get(parentId);
        arrayList.add(destination);
        toasts(arrayList,destination.getParentId());
        return arrayList;
    }*/
    public List<Destination> toasts( String destId) {
        List<Destination> arrayList = new ArrayList<>();
        while (StringUtils.hasLength(destId)) {
            Destination destination = this.get(destId);
            destId = destination.getParentId();
            arrayList.add(destination);
        }
        //集合反转
        Collections.reverse(arrayList);
        return arrayList;
    }

    /**
     * 根据区域id获取目的地,特殊处理国内的情况
     * @param regionId
     * @return
     */
    @Override
    public List<Destination> search(String regionId) {
        List<Destination> list;
        if ("-1".equals(regionId)) {
            list = destinationRepository.findByParentName("中国");
        }else {
            list = this.queryByRegionId(regionId);
        }
        list.forEach(d -> {
            //List<Destination> l = mongoTemplate.find(Query.query(Criteria.where("parentId").is(d.getId())).skip(0).limit(5),Destination.class);
            //只查前5条数据
            Pageable pageable = PageRequest.of(0,5);
            List<Destination> l = destinationRepository.findByParentId(pageable,d.getId());
            d.setChildren(l);
        });
        return list;
    }

    /**
     * 根据层面查询目的地
     * @param deep
     * @return
     */
    @Override
    public List<Destination> queryByDeep(Integer deep) {
        return destinationRepository.findByDeep(deep);
    }

    /**
     * 根据name查询目的地
     * @param name
     * @return
     */
    @Override
    public Destination queryByName(String name) {
        return destinationRepository.findByName(name);
    }

    /**
     * 根据目的地id查询攻略分类及分类下的全部攻略
     * TODO 这个方法要移值到攻略分类中
     * @return
     */
    @Override
    public List<StrategyCatalog> queryCatalog(String destId) {
        List<StrategyCatalog> strategyCatalogs = strategyCatalogService.queryCatalogByDeatId(destId);
        for (StrategyCatalog strategyCatalog : strategyCatalogs) {
            List<Strategy> strategies = strategyService.queryByCatalogId(strategyCatalog.getId());
            strategyCatalog.setStrategies(strategies);
        }
        return strategyCatalogs;
    }

}
